package cn.xdwanj.ask.response;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author xdwanj
 */
@Setter
@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResponse<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    @Schema(description = "状态码")
    private Integer code;
    @Schema(description = "消息")
    private String msg;
    @Schema(description = "数据")
    private T data;

    @JsonIgnore
    public boolean isSuccess() {
        return ResponseCode.SUCCESS.code.equals(this.code);
    }

    private CommonResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> CommonResponse<T> get(String msg, Integer code, T data) {
        return new CommonResponse<>(code, msg, data);
    }

    public static <T> CommonResponse<T> success(String msg, T data) {
        return new CommonResponse<>(ResponseCode.SUCCESS.code, msg, data);
    }

    public static <T> CommonResponse<T> success(String msg) {
        return new CommonResponse<>(ResponseCode.SUCCESS.code, msg, null);
    }

    public static <T> CommonResponse<T> successByData(T data) {
        return new CommonResponse<>(ResponseCode.SUCCESS.code, null, data);
    }

    public static <T> CommonResponse<T> success() {
        return new CommonResponse<>(ResponseCode.SUCCESS.code, null, null);
    }

    public static <T> CommonResponse<T> error(String msg, Integer code) {
        return new CommonResponse<>(code, msg, null);
    }

    public static <T> CommonResponse<T> error(String msg) {
        return error(msg, ResponseCode.ERROR.code);
    }

    public static <T> CommonResponse<T> error() {
        return error(null, ResponseCode.ERROR.code);
    }

    @Override
    public String toString() {
        return "{"
            + "\"code\": " + this.getCode()
            + ", \"msg\": " + transValue(this.getMsg())
            + ", \"data\": " + transValue(this.getData())
            + "}";
    }

    private String transValue(Object value) {
        if (value instanceof String) {
            return "\"" + value + "\"";
        }
        return String.valueOf(value);
    }
}



